<template>
  <div class="app-container">
    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
      <el-form-item label="年级：" prop="gradeLevel" required>
        <el-select v-model="form.gradeLevel" placeholder="年级" clearable>
          <el-option
            v-for="item in classList"
            :key="item.id"
            :value="item.id"
            :label="item.gradeLevel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科：" prop="subjectId" required>
        <el-select v-model="form.subjectId" placeholder="学科">
          <el-option
            v-for="(value, key) in subjectEnum"
            :key="key"
            :value="+key"
            :label="value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目类型：" prop="questionType" required>
        <el-select v-model="form.questionType" placeholder="题目类型" :disabled="submitType === 1">
          <el-option
            v-for="(value, key) in questionTypeEnum"
            :key="key"
            :value="+key"
            :label="value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干：" prop="title" required>
        <el-input v-model="form.title" @focus="inputClick(form, 'title')" />
      </el-form-item>

      <el-form-item label="选项：" required>
        <el-button type="success" @click="questionItemAdd">添加选项</el-button>

        <el-form-item
          :label="item.prefix"
          :key="item.prefix"
          v-for="(item, index) in form.items"
          label-width="50px"
          class="question-item-label"
        >
          <el-input v-model="item.prefix" style="width: 50px;" />
          <el-input
            v-model="item.content"
            @focus="inputClick(item, 'content')"
            class="question-item-content-input"
          />
          <el-button
            type="danger"
            size="mini"
            class="question-item-remove"
            icon="el-icon-delete"
            @click="questionItemRemove(index)"
          ></el-button>
        </el-form-item>
      </el-form-item>
      <el-form-item
        label="正确答案："
        prop="correct"
        required
        v-if="form.questionType && form.questionType !== 2"
      >
        <el-radio-group v-model="form.correct">
          <el-radio v-for="item in form.items" :key="item.prefix" :label="item.prefix">{{
            item.prefix
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="正确答案："
        prop="correctArray"
        required
        v-if="form.questionType && form.questionType === 2"
      >
        <el-checkbox-group v-model="form.correctArray">
          <el-checkbox v-for="item in form.items" :label="item.prefix" :key="item.prefix">{{
            item.prefix
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="解析：" prop="analyze" required>
        <el-input v-model="form.analyze" @focus="inputClick(form, 'analyze')" />
      </el-form-item>
      <el-form-item label="分数：" prop="score" required>
        <el-input-number v-model="form.score" :precision="1" :step="1" :max="100"></el-input-number>
      </el-form-item>
      <el-form-item label="难度：" required>
        <el-rate v-model="form.difficult" class="question-item-rate"></el-rate>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <!-- <el-button type="success" @click="showQuestion">预览</el-button> -->
      </el-form-item>
    </el-form>
    <!-- 富文本 -->
    <el-dialog
      :visible.sync="richEditor.dialogVisible"
      v-if="richEditor.dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      style="width: 100%; height: 100%;"
      :show-close="false"
      title="编辑内容"
    >
      <Editor @ready="editorReady" />
      <span slot="footer">
        <el-button type="primary" @click="editorConfirm">确 定</el-button>
        <el-button @click="richEditor.dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    detailQuestion,
    addQuestion,
    editQuestion,
    getChapterTree
  } from '@/api/TeachingCenter/questionManage'
  import { getClassList } from '@/api/TeachingCenter/classManage'
  import Descriptions from '@/components/Descriptions'
  import Editor from '@/components/Editor'
  import Mixin from './mixin'
  import { mapGetters } from 'vuex'
  export default {
    name: 'EditQuestion',
    components: { Descriptions, Editor },
    mixins: [Mixin],
    data() {
      return {
        detailData: {},
        subjectList: [],
        classList: [],
        submitType: 0, //0：新增，1：修改，2：详情
        richEditor: {
          dialogVisible: false,
          object: null,
          instance: null
        },
        form: {
          id: null,
          questionType: null,
          gradeLevel: null,
          subjectId: null,
          title: '',
          items: [
            // { prefix: 'A', content: '' },
            // { prefix: 'B', content: '' },
            // { prefix: 'C', content: '' },
            // { prefix: 'D', content: '' }
          ],
          analyze: '',
          correct: '',
          correctArray: [],
          score: '',
          difficult: 0
        },
        rules: {
          gradeLevel: [{ required: true, message: '请选择年级', trigger: 'change' }],
          subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }],
          questionType: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
          title: [{ required: true, message: '请输入题干', trigger: 'blur' }],
          analyze: [{ required: true, message: '请输入解析', trigger: 'blur' }],
          score: [{ required: true, message: '请输入分数', trigger: 'blur' }],
          correct: [{ required: true, message: '请选择正确答案', trigger: 'change' }]
        },
        formLoading: false
      }
    },
    computed: {
      ...mapGetters(['questionTypeEnum', 'subjectEnum'])
    },
    created() {
      const { id, type } = this.$route.query
      this._getClassList()
      this._getChapterTree()
      if (id) {
        this.getQuestionDetail(id)
        this.submitType = +type
      }
    },
    methods: {
      async getQuestionDetail(id) {
        const { data } = await detailQuestion(id)
        this.form = data
      },
      async _getClassList() {
        const { data } = await getClassList({})
        console.log(data)
        this.classList = data.records
      },
      async _getChapterTree() {
        const { data } = await getChapterTree()
        console.log(data)
        // this.classList = data.records
      },
      async submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const submitFun = [addQuestion, editQuestion]
            this.formLoading = true
            submitFun[this.submitType](this.form)
              .then((res) => {
                this.$Msg.success(res.message)
                this.formLoading = false
                this.$router.push('./list')
              })
              .catch((e) => {
                this.formLoading = false
              })
          } else {
            return false
          }
        })
      },
      editorReady(instance) {
        this.richEditor.instance = instance
        let currentContent = this.richEditor.object[this.richEditor.parameterName]
        this.richEditor.instance.txt.html(currentContent)
        // 光标定位到editor
        this.richEditor.instance.focus(true)
      },
      inputClick(object, parameterName) {
        this.richEditor.object = object
        this.richEditor.parameterName = parameterName
        this.richEditor.dialogVisible = true
      },
      editorConfirm() {
        let content = this.richEditor.instance.txt.html()
        this.richEditor.object[this.richEditor.parameterName] = content
        this.richEditor.dialogVisible = false
      },
      questionItemAdd() {
        let items = this.form.items
        let newLastPrefix
        if (!this.form.questionType) {
          this.$Msg.error('请选择题目类型')
          return
        }
        if (this.form.questionType === 3) {
          if (items.length >= 2) {
            this.$Msg.error('最多只能添加两项')
            return
          }
        }
        if (items.length > 0) {
          let last = items[items.length - 1]
          newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
        } else {
          newLastPrefix = 'A'
        }
        items.push({ id: null, prefix: newLastPrefix, content: '' })
      },
      questionItemRemove(index) {
        this.form.items.splice(index, 1)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .q-content {
    display: inline-block;
    .q-item-contain {
      display: inline-block;
      .q-item-prefix {
        margin: 5px 10px;
      }
      .q-item-content {
        margin: 5px;
        white-space: normal;
      }
    }
  }
</style>
